<template>
  <div>
    <div class="search-bar">
      <el-row gutter="20">
        <el-col :span="5">
          <el-select v-model="form.repairState" placeholder="请选择状态" clearable>
            <el-option
                v-for="item in statusOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            ></el-option>
          </el-select>
        </el-col>
        <el-col :span="5">
          <el-select v-model="form.repairArea" placeholder="请选择维修区域" clearable>
            <el-option
                v-for="item in regionOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            ></el-option>
          </el-select>
        </el-col>
        <el-col :span="5">
          <el-select v-model="form.repairCategoryId" placeholder="请选择报修项目" clearable>
            <el-option
                v-for="item in projectOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            ></el-option>
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-input v-model="form.repairUserName" placeholder="请输入报修人姓名" clearable></el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="onSubmit">查询</el-button>
        </el-col>
      </el-row>
    </div>
    <!-- 标签页 -->
    <el-tabs v-model="activeName" type="border-card" @tab-click="handleClick">
      <el-tab-pane label="全部" name="all">
        <div class="search-bar">
          <el-table :data="allData" style="width: 100%">
            <el-table-column fixed prop="repairNum" label="编号"/>
            <el-table-column prop="repairInfo" label="区域"/>
            <el-table-column prop="repairType" label="项目"/>
            <el-table-column prop="repairUserName" label="报修人"/>
            <el-table-column prop="repairTime" label="报修时间"/>
            <el-table-column prop="repairPersonName" label="受理人"/>
            <el-table-column prop="repairTakeTime" label="受理用时"/>
            <el-table-column prop="state" label="状态"/>
            <el-table-column fixed="right" label="操作">
              <template #default="scope">
                <el-button size="mini"
                           @click="selectRepairById(scope.row.repairId, scope.row.repairNum)">
                  查看详情
                </el-button>
                <el-button v-if="scope.row.repairState === 0"  type="success" size="mini"
                           @click="openDispatchDialog(scope.row.repairNum)">
                  派单
                </el-button>
                <el-button v-if="scope.row.repairState === 0" type="danger" size="mini"
                           @click="openRejectDialog(scope.row.repairNum)">
                  驳回
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <!-- 分页组件 -->
        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[5, 10, 20]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next"
            :total="totalItems"
        ></el-pagination>
      </el-tab-pane>
      <el-tab-pane label="本年" name="year">
        <div class="search-bar">
          <el-table :data="allData" style="width: 100%">
            <el-table-column fixed prop="repairNum" label="编号"/>
            <el-table-column prop="repairInfo" label="区域"/>
            <el-table-column prop="repairType" label="项目"/>
            <el-table-column prop="repairUserName" label="报修人"/>
            <el-table-column prop="repairTime" label="报修时间"/>
            <el-table-column prop="repairPersonName" label="受理人"/>
            <el-table-column prop="repairTakeTime" label="受理用时"/>
            <el-table-column prop="state" label="状态"/>
            <el-table-column fixed="right" label="操作">
              <template #default="scope">
                <el-button size="mini"
                           @click="selectRepairById(scope.row.repairId, scope.row.repairNum)">
                  查看详情
                </el-button>
                <el-button v-if="scope.row.repairState === 0"  type="success" size="mini"
                           @click="openDispatchDialog(scope.row.repairNum)">
                  派单
                </el-button>
                <el-button v-if="scope.row.repairState === 0" type="danger" size="mini"
                           @click="openRejectDialog(scope.row.repairNum)">
                  驳回
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <!-- 分页组件 -->
        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[5, 10, 20]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next"
            :total="totalItems"
        ></el-pagination>·
      </el-tab-pane>
      <el-tab-pane label="本月" name="month">
        <div class="search-bar">
          <el-table :data="allData" style="width: 100%">
            <el-table-column fixed prop="repairNum" label="编号"/>
            <el-table-column prop="repairInfo" label="区域"/>
            <el-table-column prop="repairType" label="项目"/>
            <el-table-column prop="repairUserName" label="报修人"/>
            <el-table-column prop="repairTime" label="报修时间"/>
            <el-table-column prop="repairPersonName" label="受理人"/>
            <el-table-column prop="repairTakeTime" label="受理用时"/>
            <el-table-column prop="state" label="状态"/>
            <el-table-column fixed="right" label="操作">
              <template #default="scope">
                <el-button size="mini"
                           @click="selectRepairById(scope.row.repairId, scope.row.repairNum)">
                  查看详情
                </el-button>
                <el-button v-if="scope.row.repairState === 0"  type="success" size="mini"
                           @click="openDispatchDialog(scope.row.repairNum)">
                  派单
                </el-button>
                <el-button v-if="scope.row.repairState === 0" type="danger" size="mini"
                           @click="openRejectDialog(scope.row.repairNum)">
                  驳回
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <!-- 分页组件 -->
        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[5, 10, 20]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next"
            :total="totalItems"
        ></el-pagination>
      </el-tab-pane>
      <el-tab-pane label="本周" name="week">
        <div class="search-bar">
          <el-table :data="allData" style="width: 100%">
            <el-table-column fixed prop="repairNum" label="编号"/>
            <el-table-column prop="repairInfo" label="区域"/>
            <el-table-column prop="repairType" label="项目"/>
            <el-table-column prop="repairUserName" label="报修人"/>
            <el-table-column prop="repairTime" label="报修时间"/>
            <el-table-column prop="repairPersonName" label="受理人"/>
            <el-table-column prop="repairTakeTime" label="受理用时"/>
            <el-table-column prop="state" label="状态"/>
            <el-table-column fixed="right" label="操作">
              <template #default="scope">
                <el-button size="mini"
                           @click="selectRepairById(scope.row.repairId, scope.row.repairNum)">
                  查看详情
                </el-button>
                <el-button v-if="scope.row.repairState === 0"  type="success" size="mini"
                           @click="openDispatchDialog(scope.row.repairNum)">
                  派单
                </el-button>
                <el-button v-if="scope.row.repairState === 0" type="danger" size="mini"
                           @click="openRejectDialog(scope.row.repairNum)">
                  驳回
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <!-- 分页组件 -->
        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[5, 10, 20]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next"
            :total="totalItems"
        ></el-pagination>
      </el-tab-pane>
      <el-tab-pane label="昨天" name="yesterday">
        <div class="search-bar">
          <el-table :data="allData" style="width: 100%">
            <el-table-column fixed prop="repairNum" label="编号"/>
            <el-table-column prop="repairInfo" label="区域"/>
            <el-table-column prop="repairType" label="项目"/>
            <el-table-column prop="repairUserName" label="报修人"/>
            <el-table-column prop="repairTime" label="报修时间"/>
            <el-table-column prop="repairPersonName" label="受理人"/>
            <el-table-column prop="repairTakeTime" label="受理用时"/>
            <el-table-column prop="state" label="状态"/>
            <el-table-column fixed="right" label="操作">
              <template #default="scope">
                <el-button size="mini"
                           @click="selectRepairById(scope.row.repairId, scope.row.repairNum)">
                  查看详情
                </el-button>
                <el-button v-if="scope.row.repairState === 0"  type="success" size="mini"
                           @click="openDispatchDialog(scope.row.repairNum)">
                  派单
                </el-button>
                <el-button v-if="scope.row.repairState === 0" type="danger" size="mini"
                           @click="openRejectDialog(scope.row.repairNum)">
                  驳回
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <!-- 分页组件 -->
        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[5, 10, 20]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next"
            :total="totalItems"
        ></el-pagination>
      </el-tab-pane>
      <el-tab-pane label="今天" name="today">
        <div class="search-bar">
          <el-table :data="allData" style="width: 100%">
            <el-table-column fixed prop="repairNum" label="编号"/>
            <el-table-column prop="repairInfo" label="区域"/>
            <el-table-column prop="repairType" label="项目"/>
            <el-table-column prop="repairUserName" label="报修人"/>
            <el-table-column prop="repairTime" label="报修时间"/>
            <el-table-column prop="repairPersonName" label="受理人"/>
            <el-table-column prop="repairTakeTime" label="受理用时"/>
            <el-table-column prop="state" label="状态"/>
            <el-table-column fixed="right" label="操作">
              <template #default="scope">
                <el-button size="mini"
                           @click="selectRepairById(scope.row.repairId, scope.row.repairNum)">
                  查看详情
                </el-button>
                <el-button v-if="scope.row.repairState === 0"  type="success" size="mini"
                           @click="openDispatchDialog(scope.row.repairNum)">
                  派单
                </el-button>
                <el-button v-if="scope.row.repairState === 0" type="danger" size="mini"
                           @click="openRejectDialog(scope.row.repairNum)">
                  驳回
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <!-- 分页组件 -->
        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[5, 10, 20]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next"
            :total="totalItems"
        ></el-pagination>
      </el-tab-pane>
    </el-tabs>

    <!-- 弹窗 -->
    <el-dialog v-model="dialogVisible" width="50%">
      <span class="bold-large">请选择维修人员</span>
      <div class="search-bar">
      <el-table :data="repairers" style="width: 100%" @row-click="handleRowClick" @selection-change="handleSelectionChange">
        <el-table-column type="selection"/>
        <el-table-column prop="userName" label="姓名"/>
        <el-table-column prop="profession" label="专业"/>
        <el-table-column prop="expand2" label="区域"/>
      </el-table>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmDispatch">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 驳回弹窗 -->
    <el-dialog v-model="rejectDialogVisible" width="30%">
      <span class="bold-large">驳回工单</span>
      <el-form :model="rejectForm" label-width="100px">
        <el-form-item label="驳回原因">
          <el-input v-model="rejectForm.reason" type="textarea" :rows="4" placeholder="请输入驳回原因"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="rejectDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmReject">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      form: {
        repairState: '',
        repairArea: '',
        repairCategoryId: '',
        repairUserName: '', // 修改为 repairUserName 以匹配后端参数
      },
      statusOptions: [
        {value: 1, label: '已分配'},
        {value: 2, label: '维修中'},
        {value: 3, label: '维修完成'},
        {value: 4, label: '已驳回'},
        {value: 5, label: '已取消'},
        {value: 0, label: '待审核'}
      ],
      projectOptions: [],
      currentPage: 1,
      pageSize: 10,
      totalItems: 0,
      allData: [],
      dialogVisible: false,
      repairers: [],
      currentRepairNum: '',
      regionOptions: [],
      rejectDialogVisible: false,
      rejectForm: {
        reason: ''
      },
      activeName: 'all',
      selectedRepairer: null,
      selectedRows: [], // 新增用于存储选中的行
    };
  },
  mounted() {
    this.fetchData('all'); // 默认加载全部数据
    this.fetchRepairCategories();
    this.fetchRegionOptions();
  },
  methods: {
    handleClick({ props }) {
      if (!props || !props.name) {
        console.error('无效的标签对象:', props);
        return;
      }
      const currentYear = new Date().getFullYear();
      const currentMonth = String(new Date().getMonth() + 1).padStart(2, '0');
      const currentDate = String(new Date().getDate()).padStart(2, '0');
      const today = `${currentYear}-${currentMonth}-${currentDate}`;

      switch (props.name) {
        case 'year':
          this.startDate = `${currentYear}-01-01`;
          this.endDate = `${currentYear}-12-31`;
          break;
        case 'month':
          this.startDate = `${currentYear}-${currentMonth}-01`;
          this.endDate = `${currentYear}-${currentMonth}-${new Date(currentYear, currentMonth, 0).getDate()}`;
          break;
        case 'week':
          const firstDayOfWeek = new Date();
          firstDayOfWeek.setDate(firstDayOfWeek.getDate() - firstDayOfWeek.getDay());
          const lastDayOfWeek = new Date();
          lastDayOfWeek.setDate(firstDayOfWeek.getDate() + 6);
          this.startDate = firstDayOfWeek.toISOString().split('T')[0];
          this.endDate = lastDayOfWeek.toISOString().split('T')[0];
          break;
        case 'yesterday':
          const yesterday = new Date();
          yesterday.setDate(yesterday.getDate() - 1);
          const year = yesterday.getFullYear();
          const month = String(yesterday.getMonth() + 1).padStart(2, '0');
          const day = String(yesterday.getDate()).padStart(2, '0');
          this.startDate = `${year}-${month}-${day}`;
          this.endDate = `${year}-${month}-${day}`;
          break;
        case 'today':
          this.startDate = today;
          this.endDate = today;
          break;
        default:
          this.startDate = '';
          this.endDate = '';
          break;
      }
      this.selectRepairList(); // 重新获取数据
    },
    handleRowClick(row) {
      this.selectedRepairer = row;
    },
    openRejectDialog(repairNum) {
      this.rejectDialogVisible = true;
      this.rejectForm.reason = ''; // 清空上次输入的驳回原因
      this.currentRepairNum = repairNum; // 存储当前维修单ID
    },
    async confirmReject() {
      if (!this.rejectForm.reason) {
        this.$message.warning('请输入驳回原因');
        return;
      }
      try {
        const response = await axios.put('/repaircenter/repair/rejectRepair', {
          repairNum: this.currentRepairNum,
          description: this.rejectForm.reason
        });
        this.selectRepairList(); // 刷新列表
        this.rejectDialogVisible = false;
      } catch (error) {
        console.error('驳回失败', error);
      }
    },
    onSubmit() {
      this.currentPage = 1; // 重置当前页码为第一页
      this.selectRepairList(); // 根据表单数据查询数据
    },
    async fetchRepairCategories() {
      try {
        const response = await axios.get("/repaircenter/repairCategory/listAll");

        if (response.data.code === 200) {
          this.projectOptions = response.data.data.map((category) => ({
            value: category.repairCategoryId, // 假设返回的数据中有一个 repairCategoryId 字段作为 value
            label: category.categoryName, // 假设返回的数据中有一个 categoryName 字段作为 label
          }));
        } else {
          this.$message.error("获取维修类型列表失败");
        }
      } catch (error) {
        this.$message.error("获取维修类型列表失败");
        console.error(error);
      }
    },
    async fetchRegionOptions() {
      try {
        const response = await axios.get("/user/areaCode/listAreaCode");
        if (response.data.code === 200) {
          this.regionOptions = response.data.data.map((area) => ({
            value: area.areaCodeId, // 使用区域ID作为value
            label: area.areaCodeName // 使用区域名称作为label
          }));
        } else {
          this.$message.error("获取区域列表失败");
        }
      } catch (error) {
        this.$message.error("获取区域列表失败");
        console.error(error);
      }
    },
    async fetchData(tabName) {
      this.activeName = tabName;
      this.selectRepairList();
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.selectRepairList();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.selectRepairList();
    },
    async selectRepairList() {
      try {
        const response = await axios.post('/repaircenter/repair/selectRepairList', {
          repairState: this.form.repairState,
          repairArea: this.form.repairArea,
          repairCategoryId: this.form.repairCategoryId,
          repairUserName: this.form.repairUserName,
          pageNum: this.currentPage, // 当前页码
          pageSize: this.pageSize, // 每页显示数量
          startDate: this.startDate || null, // 确保传递了 startDate
          endTime: this.endDate || null // 确保传递了 endDate
        });

        if (response.data.code === 200 && response.data.data && response.data.data.list) {
          this.allData = response.data.data.list;
          this.totalItems = response.data.data.total;
        } else {
          console.error('Invalid response format:', response.data);
        }
      } catch (error) {
        console.error('查询维修记录失败', error);
      }
    },
    async selectRepairById(repairId, repairNum) {
      this.$router.push({name: 'RepairAdminInfo', params: {id: repairId, num: repairNum}});
    },
    async dispatchRepair(data) {
      try {
        const response = await axios.put('/repaircenter/repair/dispatchRepair', data, {
          headers: {
            token: localStorage.getItem('token')
          }
        });
        this.selectRepairList(); // 刷新列表
      } catch (error) {
        console.error('派单失败', error);
      }
    },
    openDispatchDialog(repairNum) {
      const selectedRepair = this.allData.find(repair => repair.repairNum === repairNum);
      if (!selectedRepair) {
        this.$message.error('未找到对应的维修单');
        return;
      }

      this.selectedRepairer = null; // 清空上次选择的维修人员
      this.currentRepairNum = repairNum; // 存储当前维修单号

      // 根据区域名称获取维修人员
      this.fetchRepairersByArea(selectedRepair.repairArea);
      this.dialogVisible = true;
    },
    handleSelectionChange(selection) {
      this.selectedRows = selection;
      if (this.selectedRows.length > 0) {
        this.selectedRepairer = this.selectedRows[0]; // 假设只允许选择一行
      } else {
        this.selectedRepairer = null;
      }
    },
    async fetchRepairersByArea(areaName) {
      try {
        const response = await axios.get('/user/employeeInfo/queryWorkerList', {params:{areaCodeId: areaName}});
        if (response.data.code === 200 ) {
          this.repairers = response.data.data;
        } else {
          this.$message.error('已无空闲维修人员');
        }
      } catch (error) {
        console.error('获取维修人员列表失败', error);
        this.$message.error('获取维修人员列表失败');
      }
    },
    confirmDispatch() {
      if (!this.selectedRepairer) {
        this.$message.warning('请选择维修人员');
        return;
      }

      this.dispatchRepair({
        repairNum: this.currentRepairNum,
        repairPerson: this.selectedRepairer.userId,
        repairPersonName: this.selectedRepairer.userName
      });
      this.dialogVisible = false;
    },
  }
};
</script>

<style scoped>
.search-bar {
  width: 100%;
  margin-bottom: 15px;
}


.bold-large {
  font-weight: bold;
  font-size: 1.5em; /* 调整字体大小，可以根据需要调整 */
}
.custom-select {
  width: 200px; /* 根据需要调整宽度 */
}
</style>